import { md5 } from './Md5'
import { sys } from 'cc'

const serviceHost = 'https://www.cxgame.net/wxgame/'
const signKey = '2908953aecf9896815902cb2028da8ae'
const saveProfileUrl = 'set-profile'
const getProfileUrl = 'get-profile'
const submitWorldScoreUrl = 'submit-score'
const getWorldRankDataUrl = 'get-rank'

/**
 * submitWorldScore
 * getWorldRankData
 */

export class WXGameService {
	static postData<T>(url = '', params = {}): Promise<T> {
		return new Promise((resolve, reject) => {
			const xhr = new XMLHttpRequest()
			xhr.open('POST', url, true)
			if (sys.isNative) {
				xhr.setRequestHeader('Accept-Encoding', 'gzip,deflate')
			}
			xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
			// note: In Internet Explorer, the timeout property may be set only after calling the open()
			// method and before calling the send() method.
			xhr.timeout = 30000 // 30 seconds for timeout

			var paramStr = ''
			for (var item in params) {
				paramStr += item + '=' + encodeURIComponent(params[item]) + '&'
			}
			xhr.send(paramStr)
			xhr.onreadystatechange = () => {
				if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status <= 500) {
					var response = xhr.responseText
					resolve(JSON.parse(response))
				}
			}
		})
	}

	static parseQueryString(obj) {
		let str = ''
		for (let key in obj) {
			str += key + '=' + obj[key] + '&'
		}
		return str
	}

	static generatePar(par) {
		const sdic = Object.keys(par).sort()
		const content_list = []
		for (var ki in sdic) {
			content_list.push(sdic[ki] + '=' + par[sdic[ki]])
		}
		let content = content_list.join('&')
		content += signKey
		const sign = md5(content)
		par.sign = sign
	}

	static getProfile<T>(appId: string, uid: string): Promise<T> {
		const par = {
			app_id: appId,
			uid: uid,
		}
		this.generatePar(par)
		return this.postData(serviceHost + getProfileUrl, par)
	}

	static saveProfile<T>(appId: string, uid: string, profile: T): Promise<void> {
		const par = {
			app_id: appId,
			uid: uid,
			profile: JSON.stringify(profile),
		}
		this.generatePar(par)
		return this.postData(serviceHost + saveProfileUrl, par)
	}

	static submitWorldScore(app_id, uid, rank_key, score, info) {
		console.log('submitWorldScore ' + app_id + ' ' + uid + ' ' + rank_key + ' ' + score)
		console.log(info)
		if (!app_id) {
			return
		}
		if (!uid) {
			return
		}
		if (!rank_key) {
			return
		}
		var par = {
			app_id: app_id,
			uid: uid,
			key: rank_key,
			score: score,
			info: info,
		}
		this.generatePar(par)
		return this.postData(serviceHost + submitWorldScoreUrl, par)
	}

	static getWorldRankData(app_id, uid, rank_key, group, count) {
		if (!group) {
			group = ''
		}
		var par = {
			app_id: app_id,
			uid: uid,
			key: rank_key,
			group: group,
			count: count,
		}
		this.generatePar(par)
		return this.postData(serviceHost + getWorldRankDataUrl, par)
	}
}
